#include "qfilesearchdialog.h"

#include "Qt/miniaudio.h"
#include "Utilities/FolderUtilities.h"

#include <QSqlQuery>
#include <QVBoxLayout>
#include <qobject.h>

QFileSearchDialog::QFileSearchDialog(QWidget *parent, QString databasePath)
    : QDialog(parent)
    , m_searchTimer(new QTimer(this))
{
    QString path = databasePath.isEmpty() ? QString::fromStdString(FolderUtilities::GetHomeFolder()) + "/file_index.db" : databasePath;
    m_database = QSqlDatabase::addDatabase("QSQLITE");
    m_database.setDatabaseName(path);
    m_database.open();

    setWindowTitle(tr("文件选择对话框"));

    initializeUI();
}

QFileSearchDialog::~QFileSearchDialog()
{
    if (m_database.isOpen()) {
        m_database.close();
    }
    QSqlDatabase::removeDatabase(m_database.connectionName());
}

QString QFileSearchDialog::selectedFile() const
{
    QList<QListWidgetItem *> selectedItems = m_resultsListWidget->selectedItems();
    if (!selectedItems.isEmpty()) {
        return selectedItems.first()->text();
    }
    return QString();
}

void QFileSearchDialog::initializeUI()
{
    m_searchLineEdit = new QLineEdit(this);
    m_searchLineEdit->setPlaceholderText(tr("搜索文件..."));

    m_searchTimer->setInterval(200);
    connect(m_searchTimer, &QTimer::timeout, this, [this]() {
        QString query = m_searchLineEdit->text().trimmed();
        if (!query.isEmpty()) {
            searchFiles(query);
        } else {
            m_resultsListWidget->clear();
        }
    });

    connect(m_searchLineEdit, &QLineEdit::textChanged, this, [this]() {
        if (m_searchTimer->isActive())
            m_searchTimer->stop();
        m_searchTimer->start();
    });

    m_resultsListWidget = new QListWidget(this);
    m_resultsListWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    m_resultsListWidget->setSortingEnabled(true);
    m_resultsListWidget->setDragEnabled(false);

    connect(m_resultsListWidget, &QListWidget::itemPressed, this, [this](QListWidgetItem *item) {
        accept(); // Close dialog and return selected file
    });

    // Layout setup
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(m_searchLineEdit);
    layout->addWidget(m_resultsListWidget);
    setLayout(layout);

    resize(600, 400);
}

void QFileSearchDialog::searchFiles(const QString &query)
{
    if (!m_database.isOpen()) {
        return;
    }

    QSqlQuery queryResult(m_database);
    queryResult.prepare("SELECT path FROM files WHERE name LIKE :query");
    queryResult.bindValue(":query", "%" + query + "%");
    if (!queryResult.exec()) {
        return;
    }

    m_resultsListWidget->clear();
    while (queryResult.next()) {
        QString filePath = queryResult.value(0).toString();
        m_resultsListWidget->addItem(filePath);
    }
}